<template>
  <div class="dashboard-container">
    <el-form ref="form" :model="form" label-width="80px" class="home_form">
      <el-form-item label="用户名">
        <el-input v-model="form.username" disabled />
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="form.nickname" />
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:3000/express/avatar"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.uAvatar" :src="form.uAvatar" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form.uEmail" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import roleApi from '@/api/roleManage'
import userApi from '@/api/userManage'
export default {
  name: 'Dashboard',
  computed: mapGetters([
    'token'
  ]),
  data() {
    return {
      roleList: [],
      form: {
        roles: []
      }
    }
  },
  created() {
    this.getAllRoleList()
    this.getUserInfo()
  },
  methods: {
    getUserInfo() {
      const token = this.token
      // console.log(token)
      userApi.getUserInfo(token).then(response => {
        // console.log(response)
        this.form = response.data
      })
    },
    getAllRoleList() {
      roleApi.getAllRoleList().then(response => {
        this.roleList = response.data
        console.log(this.roleList)
      })
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      console.log(file)
      this.userForm.uavatar = URL.createObjectURL(file.raw)
      // this.userForm.uavatar = URL.createObjectURL(res.url)
      this.userForm.uavatar = res.url
    },
    beforeAvatarUpload(file) {
      console.log(file)
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    onSubmit() {
      console.log('submit!')
    }
  }
}
</script>

<style lang="scss" scoped>
.home_form {
  width: 55%;
  .avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
  }
}
</style>
